<template>
    <div>
        <Header></Header>
        <div class="container-pc">
            <div class="setting-container">
                <div class="main-content">
                    <div class="left-content">
                        <div class="label-item label-active" id="btn_j" @click="bang(1)">
                            基本设置
                        </div>

                        <div class="label-item" id="btn_p" @click="bang(2)">
                            修改密码
                        </div>
                    </div>
                    <div class="right-content">
                        <div class="label-one" id="label-one">
                            <div class="head-pic">
                                头像
                            </div>
                            <div style='width:150px;'>
                                <el-upload class="avatar-uploader" action="1" list-type="picture-card"
                                    :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
                                    :http-request="myUpload" :class="{ 'demo-httpRequestImg': httpRequestImg }">
                                    <i class="el-icon-plus"></i>
                                </el-upload>
                                <el-dialog :visible.sync="dialogVisible" append-to-body class="ImgClass">
                                    <img width="100%" :src="dialogImageUrl" alt="">
                                </el-dialog>
                            </div>
                            <div class="nick-name">
                                昵称
                            </div>
                            <div class="input-wrap"><input id="newNickName" type="text" maxlength="15"
                                    placeholder="请输入您的昵称" class="nick-input"> <em class="error"
                                    style="display: none;"></em>
                                <div class="clear"></div>
                            </div>
                            <button @click="updateInfo" class="update-info">更新信息</button>
                        </div>

                        <div class="label-three" id="label-three" style="display: none;">
                            <div class="main-title">
                                <div class="title-left">
                                    账户密码
                                </div>
                                <div class="title-right" @click="dialogFormVisible = true">
                                    修改密码
                                </div>
                            </div>
                            <div class="sub-title">
                                ******
                            </div>
                        </div>
                    </div>
                </div>
                <!---->
                <!-- Form -->
                <el-dialog title="修改密码" :visible.sync="dialogFormVisible">
                    <!-- <el-form :model="form"> -->
                    <el-form>
                        <el-form-item label="原密码">
                            <el-input v-model="oldPwd"></el-input>
                        </el-form-item>

                        <el-form-item label="新密码">
                            <el-input v-model="newPwd1"></el-input>
                        </el-form-item>

                        <el-form-item label="确认新密码">
                            <el-input v-model="newPwd2"></el-input>
                        </el-form-item>

                    </el-form>
                    <div class="dialog-footer">
                        <el-button class="confirm-button" type="primary" @click="updatePwd">确 定</el-button>
                        <el-button class="cancel-button" @click="dialogFormVisible = false">取 消</el-button>
                    </div>
                </el-dialog>
                <!---->
            </div>
        </div>

        <Footer></Footer>
    </div>
</template>

<script>
import Header from "./Header/Header"; //顶部登录条
import Footer from "./Footer/index"; //顶部登录条
import axios from 'axios'; // 添加axios导入
import { ElMessage } from 'element-plus'; // 引入Element Plus的消息组件

export default {
    name: 'Setting',
    components: {
        Header,
        Footer
    },
    data() {
        return {
            dialogImageUrl: '',//预览url
            dialogVisibleImg: false,
            httpRequestImg: false,//展示单个图片
            dialogFormVisible: false, // 修改密码的模态框不显示
            dialogVisible: false,// 隐藏的图片文件框
            user: null,// 当前登录的用户对象信息
            fileId: "",// 上传图片后，返回的fastdfs的图片地址
            oldPwd: null,// 旧密码
            newPwd1: null,// 第一次新密码
            newPwd2: null,// 第二次新密码
        };
    },
    created() {
        // 从已经登录的缓存中获取用户信息
        const userStr = localStorage.getItem("user");
        let token = localStorage.getItem("access-token");

        // 如果access-token不存在，尝试获取token
        if (!token) {
            token = localStorage.getItem("token");
        }

        // 确保两个token键名都存储了相同的值
        if (token) {
            localStorage.setItem('access-token', token);
            localStorage.setItem('token', token);
        }

        console.log('Setting.vue created - 用户信息字符串:', userStr);
        console.log('Setting.vue created - token:', token);

        if (!userStr || userStr === 'null') {
            console.log('Setting.vue - 用户信息为空，跳转到首页');
            this.$router.push("/"); //回到首页
            return;
        }
        try {
            this.user = JSON.parse(userStr);
            console.log('Setting.vue - 解析后的用户信息:', this.user);
            // 设置默认昵称
            if (this.user && this.user.content && this.user.content.realname) {
                document.getElementById("newNickName").value = this.user.content.realname;
                console.log('Setting.vue - 设置昵称:', this.user.content.realname);
            } else {
                console.log('Setting.vue - 用户信息结构不符合预期:', this.user);
            }
        } catch (error) {
            console.error('解析用户信息失败:', error);
            this.$router.push("/"); //回到首页
        }
    },
    computed: {
    },
    methods: {
        redirectLogin() {
            window.open('/frontLogin.do', '_self');
        },
        //切换tab页
        bang(i) {
            document.getElementById("btn_j").classList.remove("label-active");
            document.getElementById("btn_p").classList.remove("label-active");

            document.getElementById("label-one").style.display = "none";
            document.getElementById("label-three").style.display = "none";

            if (i == 1) {
                document.getElementById("btn_j").classList.add("label-active");
                document.getElementById("label-one").style.display = "block";
            } else if (i == 2) {
                document.getElementById("btn_p").classList.add("label-active");
                document.getElementById("label-three").style.display = "block";
            }
        },
        // 上传头像
        myUpload(content) {
            let form = new FormData();
            form.append("file", content.file);

            axios.post("http://localhost:9000/user/upload/", form)
                .then(result => {
                    this.fileId = result.data.fileId;
                    console.log('上传成功，fileId:', result.data.fileId);
                    this.httpRequestImg = true;
                    ElMessage.success('上传成功！');
                }).catch((error) => {
                    console.error('上传失败:', error);
                    ElMessage.error('上传失败！');
                });
        },
        //更新个人信息
        updateInfo() {
            const newName = document.getElementById("newNickName").value;
            if (!newName) {
                ElMessage.error("昵称不能为空！");
                return;
            }

            // 检查用户信息的结构
            console.log('当前用户信息:', this.user);

            // 判断用户信息是否有效
            const hasValidId = (this.user && this.user.id) || (this.user && this.user.content && this.user.content.id);

            if (!hasValidId) {
                console.error('用户信息无效:', this.user);
                ElMessage.error("用户信息无效，请重新登录！");
                this.$router.push("/");
                return;
            }

            // 从 localStorage 获取 token
            let token = localStorage.getItem('access-token');

            // 如果access-token不存在，尝试获取token
            if (!token) {
                token = localStorage.getItem('token');
            }

            if (!token) {
                console.error('Token不存在');
                ElMessage.error("登录已过期，请重新登录！");
                this.$router.push("/");
                return;
            }

            // 确保两个token键名都存储了相同的值
            localStorage.setItem('access-token', token);
            localStorage.setItem('token', token);

            console.log('准备发送更新请求:', {
                id: this.user.content ? this.user.content.id : this.user.id,
                realname: newName,
                icon: this.fileId || (this.user.content ? this.user.content.icon : this.user.icon) || '',
                telephone: this.user.content ? this.user.content.telephone : this.user.telephone || ''
            });
            console.log('使用的token:', token);
            console.log('请求URL:', "http://localhost:9000/user/updateUser");
            console.log('请求方法:', 'PUT');
            console.log('请求头:', {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            });

            // 使用axios发送请求
            axios({
                method: 'put',
                url: "http://localhost:9000/user/updateUser",
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                data: {
                    id: this.user.content ? this.user.content.id : this.user.id,
                    realname: newName,
                    icon: this.fileId || (this.user.content ? this.user.content.icon : this.user.icon) || '',
                    telephone: this.user.content ? this.user.content.telephone : this.user.telephone || ''
                }
            }).then(result => {
                console.log('更新成功，响应:', result);

                // 更新本地存储的用户信息
                try {
                    const userInfo = JSON.parse(localStorage.getItem('user'));
                    console.log('更新前的用户信息:', userInfo);

                    // 根据用户信息的结构更新相应的字段
                    if (userInfo && userInfo.content) {
                        // 嵌套结构
                        userInfo.content.realname = newName;
                        userInfo.content.icon = this.fileId || userInfo.content.icon;
                        localStorage.setItem('user', JSON.stringify(userInfo));
                        console.log('更新后的用户信息(嵌套结构):', userInfo);

                        // 更新当前组件的用户信息
                        this.user = userInfo;
                    } else if (userInfo) {
                        // 非嵌套结构
                        userInfo.realname = newName;
                        userInfo.icon = this.fileId || userInfo.icon;
                        localStorage.setItem('user', JSON.stringify(userInfo));
                        console.log('更新后的用户信息(非嵌套结构):', userInfo);

                        // 更新当前组件的用户信息
                        this.user = userInfo;
                    } else {
                        console.error('用户信息结构不符合预期:', userInfo);
                    }

                    // 不需要强制重新登录，只需刷新用户信息
                    this.$emit('update:user', this.user);
                    // 显示成功消息并延迟1秒后刷新页面
                    ElMessage.success("更新成功");
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000);
                } catch (error) {
                    console.error('更新本地用户信息失败:', error);
                    ElMessage.error("更新用户信息失败，请刷新页面重试");
                }
            }).catch((error) => {
                console.error('更新失败:', error);
                console.error('错误详情:', error.response);
                if (error.response?.status === 401) {
                    ElMessage.error("登录已过期，请重新登录！");
                    this.logout();
                    this.$router.push("/");
                } else {
                    ElMessage.error(error.response?.data || "更新失败！");
                }
            });
        },
        //修改密码
        updatePwd() {
            if (!this.user || !this.user.content || !this.user.content.password) {
                ElMessage.error("用户信息无效，请重新登录！");
                return;
            }

            if (this.oldPwd === this.user.content.password) {
                if (this.newPwd1 === this.newPwd2) {
                    if (!this.newPwd1) {
                        ElMessage.error("新密码不能为空！");
                        return;
                    }

                    axios.get("http://localhost:9000/user/updatePassword/", {
                        params: {
                            userid: this.user.content.id,
                            newPwd: this.newPwd2
                        }
                    }).then(result => {
                        ElMessage.success("更新密码成功，请重新登录！");
                        this.dialogFormVisible = false;
                        this.logout();
                        this.$router.push("/"); //回到首页
                    }).catch((error) => {
                        console.error('更新密码失败:', error);
                        ElMessage.error(error.response?.data?.message || "更新失败！");
                    });
                } else {
                    ElMessage.error("两次密码不一致！");
                }
            } else {
                ElMessage.error("原密码错误！");
            }
        },
        //登出
        logout() {
            localStorage.setItem("user", null);
            this.isLogin = false;

            axios.get("http://localhost:9000/user/logout")
                .then((result) => {
                    console.log('登出成功');
                })
                .catch((error) => {
                    console.error('登出失败:', error);
                });
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisibleImg = true;
        },
        handleRemove(file, fileList) {
            this.httpRequestImg = false;
            console.log(file, fileList);
        },
    },
};
</script>
<style lang="less" scoped>
.demo-httpRequestImg {
    /deep/ .el-upload--picture-card {
        display: none;
    }
}


.login-banner-blank {
    height: 90px;
}

.login-banner {
    overflow: hidden;
    font-size: 0;
    height: 90px;
    position: fixed;
    width: 100%;
    top: 0;
    z-index: 4;
    background: #fff;
    -webkit-transform: translateZ(0);
    border-bottom: 0.5px solid #E8E9EB;
}

.bg {
    position: absolute;
    width: 120px;
    height: 100%;
    top: 0;
    z-index: -1;
}

.bg-left {
    left: 0;
    transform: rotate(180deg);
}

.bg-right {
    right: 0;
}

.edu-logo {
    float: left;
    width: 84px;
    height: 84px;
    margin-left: 36px;
}

.login-txt {
    font-size: 30px;
    color: #333333;
    margin-left: 16px;
    float: left;
    margin-top: 24px;
}

.login-btn {
    float: right;
    background: #E5F7F3;
    border-radius: 2px;
    width: 122px;
    font-size: 30px;
    color: #00B38A;
    text-align: center;
    font-weight: 400;
    line-height: 30px;
    padding: 15px 0;
    margin-right: 40px;
    margin-top: 15px;
    border: none;
    outline: none;

    &:active {
        background: none;
    }
}

* {
    margin: 0;
    padding: 0;
}

div {
    display: block;
}

.container-pc {
    min-height: calc(100vh - 300px);
    background: #f8f9fa;
    content: "viewport-units-buggyfill; min-height: calc(100vh - 300px)";
}

.setting-container {
    width: 1024px;
    box-sizing: border-box;
    margin: 17px auto 0;
    padding: 0 20px;
}

.setting-container .main-content {
    margin: 66px auto 0;
    height: 400px;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
}

.setting-container .main-content .left-content {
    width: 234px;
    height: 100%;
    border-right: 1px solid #eee;
}

.setting-container .main-content .left-content .label-active {
    border-right: 2px solid #e5a817;
    color: #e5a817;
    -webkit-transform: translateX(1.5px);
    transform: translateX(1.5px);
}

.setting-container .main-content .left-content .label-item {
    height: 39px;
    line-height: 39px;
    text-align: right;
    padding-right: 62px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #555;
    cursor: pointer;
}

.setting-container .main-content .right-content {
    width: 580px;
    height: 100%;
    margin-left: 67px;
}

.setting-container .main-content .right-content .label-one .head-pic {
    text-align: left;
    height: 39px;
    font-size: 14px;
    font-family: HiraginoSansGB-W3, HiraginoSansGB;
    font-weight: 400;
    color: #555;
    line-height: 39px;
}

.setting-container .main-content .right-content .label-one .pic-wrap {
    margin: 8px 8px 20px;
    width: 80px;
    height: 80px;
    line-height: 80px;
    overflow: hidden;
    border-radius: 50%;
    text-align: center;
    font-size: 14px;
    font-family: HiraginoSansGB-W3, HiraginoSansGB;
    font-weight: 400;
    color: #555;
}

.setting-container .upload-btn {
    width: 98px;
    height: 32px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: right;
    padding: 0 9px;
    line-height: 30px;
    border-radius: 3px;
    border: 1px solid #d9d9d9;
    font-size: 14px;
    font-family: HiraginoSansGB-W3, HiraginoSansGB;
    font-weight: 400;
    color: #555;
    position: relative;
}

.setting-container .upload-btn:before {
    content: "";
    position: absolute;
    width: 15px;
    height: 15px;
    left: 9px;
    top: 6px;
    cursor: pointer;
    background: url() no-repeat;
    background-size: 100% 100%;
}

.setting-container .upload-btn .av_upload {
    opacity: 0;
    cursor: pointer;
    left: -.04rem;
    top: -.027rem;
    width: 98px;
    height: 32px;
    position: relative;
    z-index: 10;
}

.nick-name {
    padding: 0 12px;
    width: 292px;
}

input {
    font-family: Microsoft Yahei, SimSun, Arial, Helvetica Neue, Helvetica;
}

.nick-input {
    -webkit-appearance: none;
    background-color: #fff;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    box-sizing: border-box;
    color: #606266;
    display: inline-block;
    font-size: inherit;
    height: 40px;
    line-height: 40px;
    outline: 0;
    padding: 0 15px;
    -webkit-transition: border-color .2s cubic-bezier(.645, .045, .355, 1);
    transition: border-color .2s cubic-bezier(.645, .045, .355, 1);
    width: 100%;
}

.setting-container .upload-btn .change-text {
    cursor: pointer;
    position: absolute;
    top: -1px;
    left: 31px;
    z-index: 1;
}

.setting-container .main-content .right-content .label-one .nick-name {
    text-align: left;
    margin: 60px 0 20px;
    height: 14px;
    font-size: 14px;
    font-family: HiraginoSansGB-W3, HiraginoSansGB;
    font-weight: 400;
    color: #555;
    line-height: 14px;
}

.setting-container .main-content .right-content .label-one .input-wrap {
    position: relative;
    width: 292px;
    height: 40px;
}

.setting-container .main-content .right-content .label-one .update-info {
    display: block;
    margin-top: 40px;
    width: 104px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    background: #fcd766;
    border-radius: 3px;
    font-size: 16px;
    font-family: HiraginoSansGB-W3, HiraginoSansGB;
    font-weight: 400;
    color: #333;
}

a,
button,
input {
    outline: 0 none;
}

button,
input[type=button],
input[type=checkbox],
input[type=file],
input[type=radio],
input[type=reset],
input[type=submit],
label,
select {
    cursor: pointer;
}

button,
input,
optgroup,
select,
textarea {
    margin: 0;
    padding: 0;
    border: 1px solid #ededed;
    border-radius: 0;
    font-family: Hiragino Sans GB, Microsoft Yahei, SimSun, Arial, Helvetica Neue, Helvetica;
}

.setting-container .main-content .right-content .label-two {
    margin-top: 12px;
    width: 71%;
    height: 56px;
    box-sizing: border-box;
    padding-left: 76px;
    position: relative;
}

.setting-container .main-content .right-content .label-two .main-title {
    height: 30px;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    -webkit-box-pack: justify;
    -webkit-justify-content: space-between;
    justify-content: space-between;
}

.setting-container .main-content .right-content .label-two .main-title .title-left {
    height: 30px;
    font-size: 18px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #333;
    line-height: 30px;
}

.setting-container .main-content .right-content .label-two .main-title .title-right {
    height: 30px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #5580c8;
    line-height: 30px;
    cursor: pointer;
}

.setting-container .main-content .right-content .label-two .sub-title {
    height: 26px;
    font-size: 14px;
    font-family: HiraginoSansGB-W3, HiraginoSansGB;
    font-weight: 400;
    color: #555;
    line-height: 26px;
}

.setting-container .main-content .right-content .label-two:before {
    content: "";
    width: 56px;
    height: 56px;
    position: absolute;
    top: 0;
    left: 0;
    background: url() no-repeat;
    background-size: 100% 100%;
}

.setting-container .main-content .right-content .label-three {
    margin-top: 12px;
    width: 71%;
    height: 56px;
    box-sizing: border-box;
}

.setting-container .main-content .right-content .label-three .main-title {
    height: 30px;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    -webkit-box-pack: justify;
    -webkit-justify-content: space-between;
    justify-content: space-between;
}

.password-change-modal-wrap .el-dialog__footer {
    padding: 0 50px 50px;
}

.el-dialog__footer {
    padding: 10px 20px 20px;
    text-align: right;
    box-sizing: border-box;
}

.dialog-footer {
    display: block;
    font-size: 0;
    text-align: left;
}

.confirm-button {
    background: #00b38a;
    color: #fff;
}

.confirm-button {
    display: inline-block;
    vertical-align: top;
    text-align: center;
    padding: 12px 22px;
    border-radius: 3px;
    font-size: 16px;
    line-height: 16px;
    cursor: pointer;
}

.cancel-button {
    color: #00b38a;
    margin-left: .053rem;
    display: inline-block;
    vertical-align: top;
    text-align: center;
    padding: 12px 22px;
    border-radius: 3px;
    font-size: 16px;
    line-height: 16px;
    cursor: pointer;
}

.setting-container .main-content .right-content .label-three .main-title .title-left {
    height: 30px;
    font-size: 18px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #333;
    line-height: 30px;
}

.setting-container .main-content .right-content .label-three .main-title .title-right {
    height: 30px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #5580c8;
    line-height: 30px;
    cursor: pointer;
}

.setting-container .main-content .right-content .label-three .sub-title {
    height: 26px;
    font-size: 14px;
    font-family: HiraginoSansGB-W3, HiraginoSansGB;
    font-weight: 400;
    color: #555;
    line-height: 26px;
}

.el-dialog__wrapper {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    overflow: auto;
    margin: 0;
}

element.style {
    margin-top: 25vh;
    width: 500px;
}

.el-dialog--center {
    text-align: center;
}

.el-dialog {
    position: relative;
    margin: 0 auto 50px;
    background: #fff;
    border-radius: 2px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, .3);
    box-sizing: border-box;
    width: 50%;
}

.el-dialog__header {
    padding: 20px 20px 10px;
}

.el-dialog__title {
    line-height: 24px;
    font-size: 18px;
    color: #303133;
}

.el-icon-close:before {
    content: "\E6DB";
}

* {
    -webkit-tap-highlight-color: transparent;
}

* {
    margin: 0;
    padding: 0;
}

.el-dialog__headerbtn {
    position: absolute;
    top: 20px;
    right: 20px;
    padding: 0;
    background: 0 0;
    border: none;
    outline: 0;
    cursor: pointer;
    font-size: 16px;
}

.el-dialog__headerbtn .el-dialog__close {
    color: #909399;
}

[class*=" el-icon-"],
[class^=el-icon-] {
    font-family: element-icons !important;
    speak: none;
    font-style: normal;
    font-weight: 400;
    -webkit-font-feature-settings: normal;
    font-feature-settings: normal;
    font-variant: normal;
    text-transform: none;
    line-height: 1;
    vertical-align: initial;
    display: inline-block;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

em,
i {
    font-style: normal;
}
</style>